package com.hcb.location;

import java.text.DecimalFormat;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcb.location.ParseDistance;

import android.content.Context;
import android.util.Log;

public class DistanceLocation {
	private Context mContext;
	double latitude;
	double longitude;
	GPSTracker gps;
	
	public DistanceLocation(Context context){
		this.mContext = context;
		gps = new GPSTracker(this.mContext);
		if(gps.canGetLocation){
			this.latitude = gps.getLatitude();
			this.longitude = gps.getLongitude();
		}
		else {
			gps.showSettingsAlert();
		}
	}
	public double getDistance(double latitude, double longitude) throws JSONException{
		double distance=0;
		JSONObject obDistance = ParseDistance.getDistance(this.longitude, this.latitude,
				longitude, latitude);
		try {
			distance = ((JSONArray) obDistance.get("routes")).getJSONObject(0)
					.getJSONArray("legs").getJSONObject(0)
					.getJSONObject("distance").getDouble("value");
			int i = (int)convertMToMi(distance);
			return (int)convertMToMi(distance);
		} catch (Exception e) {
			// TODO: handle exception
			return CalculationByDistance(longitude, latitude);
		}
		
	}
	public double CalculationByDistance(
			double longTo, double latTo) {
		int Radius = 6371;// radius of earth in Km
		double dLat = Math.toRadians(latTo - this.latitude);
		double dLon = Math.toRadians(longTo - this.longitude);
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
				+ Math.cos(Math.toRadians(this.latitude))
				* Math.cos(Math.toRadians(latTo)) * Math.sin(dLon / 2)
				* Math.sin(dLon / 2);
		double c = 2 * Math.asin(Math.sqrt(a));
		double valueResult = Radius * c;
		double km = valueResult / 1;
		DecimalFormat newFormat = new DecimalFormat("####");
		int kmInDec = Integer.valueOf(newFormat.format(km));
		double meter = valueResult % 1000;
		int meterInDec = Integer.valueOf(newFormat.format(meter));
		Log.i("Radius Value", "" + valueResult + "   KM  " + kmInDec
				+ " Meter   " + meterInDec);

		//return Radius * c;
		return (int)convertMToMi(valueResult);
		
	}
	public double getLatitude() {
		return latitude;
	}
	
	public double getLongitude() {
		return longitude;
	}
	
	 public  double convertMToMi(double meters) {
		 	double km = meters / 1000;
		    DecimalFormat newFormat = new DecimalFormat("####");
			int kmInDec = Integer.valueOf(newFormat.format(km));
	        // Assume there are 0.621 miles in a kilometer.
	        double miles = meters * 0.000621371192;//0.621;
	        return miles;
	 }
}
